rm(list = ls())
load("dataBJPOLS.RData")

last.cases[, dups := .N, by = c("this_id")]

last.cases$type <- NA
last.cases$type[last.cases$dups == 1 & last.cases$time_period == 1] <- 1
last.cases$type[last.cases$dups == 1 & last.cases$time_period == 2] <- 2
last.cases$type[last.cases$dups == 2] <- 3

last.cases <- last.cases[last.cases$time_period == 1, ]

inst.1 <- "judgeiv_hd"
endo.1 <- "pti"
outc.1 <- "vote_post"

time.controls <- "as.factor(court_time1) + as.factor(court_time2) + as.factor(court_dow) + as.factor(severity)"
demo.controls <- "age + I(age^2) +  as.factor(race4) + female + as.factor(noteli) + regis_before + vote_pre"
case.controls <- "as.factor(any_drug) +  as.factor(any_weapon) +  as.factor(any_prop)"

form.1 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "|", inst.1, "+", time.controls))
form.2 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "+", demo.controls, "|", inst.1, "+", time.controls, "+", demo.controls))
form.3 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "+", demo.controls, "+", case.controls, "|", inst.1, "+", time.controls, "+", demo.controls, "+", case.controls))

results <- list()
run.boot <- T

if(run.boot) {
  set.seed(1231)
  for(i in 1:500) {
    out <- last.cases[, this_id_fa[sample.int(.N, .N, TRUE)], by = c("judge_cat", "court_time1")]
    last.cases.boot <- last.cases[last.cases$this_id_fa %in% out$V1, ]
    
    m1a1 <- ivreg(form.1, data = last.cases.boot)
    m1a2 <- ivreg(form.2, data = last.cases.boot)
    m1a3 <- ivreg(form.3, data = last.cases.boot)
    
    results[[i]] <- c(m1a1$coefficients["pti"], 
                      m1a2$coefficients["pti"], 
                      m1a3$coefficients["pti"])
  }
  SEs <- round(apply(do.call('rbind', results), 2, sd), 2)
}

m1a1 <- ivreg(form.1, data = last.cases)
m1a2 <- ivreg(form.2, data = last.cases)
m1a3 <- ivreg(form.3, data = last.cases)

res1_pti <- coefficients(m1a1)[grep("pti", names(coefficients(m1a1)))]
res2_pti <- coefficients(m1a2)[grep("pti", names(coefficients(m1a2)))]
res3_pti <- coefficients(m1a3)[grep("pti", names(coefficients(m1a3)))]

c1 <- c(res1_pti, SEs[1])
c2 <- c(res2_pti, SEs[2])
c3 <- c(res3_pti, SEs[3])

m1 <- data.frame(rbind(c1,
                       c2,
                       c3))

colnames(m1) <- c("estimate", "std.error")
m1$term <- c("t1", "t2", "t3")
m1_df <- data.frame(as.matrix(m1)) 
m1_df$estimate <- as.numeric(as.character(m1_df$estimate))
m1_df$std.error <- as.numeric(as.character(m1_df$std.error))
m1_df2 <- m1_df

last.cases$regis_2016 <- apply(cbind(last.cases$regis_before, last.cases$vote_2012_p, last.cases$vote_2016_p), 1, max)
outc.1 <- "I(vote_2016 * regis_2016)"

time.controls <- "as.factor(court_time1) + as.factor(court_time2) + as.factor(court_dow) + as.factor(severity)"
demo.controls <- "age + I(age^2) +  as.factor(race4) + female + as.factor(noteli) + regis_before + vote_pre"
case.controls <- "as.factor(any_drug) +  as.factor(any_weapon) +  as.factor(any_prop)"

form.1 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "|", inst.1, "+", time.controls))
form.2 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "+", demo.controls, "|", inst.1, "+", time.controls, "+", demo.controls))
form.3 <- formula(paste(outc.1, "~", endo.1, "+" , time.controls, "+", demo.controls, "+", case.controls, "|", inst.1, "+", time.controls, "+", demo.controls, "+", case.controls))

results <- list()
run.boot <- T

if(run.boot) {
  set.seed(1231)
  for(i in 1:500) {
    print(i)
    out <- last.cases[, this_id_fa[sample.int(.N, .N, TRUE)], by = c("judge_cat", "court_time1")]
    last.cases.boot <- last.cases[last.cases$this_id_fa %in% out$V1, ]
    
    m1a1 <- ivreg(form.1, data = last.cases.boot)
    m1a2 <- ivreg(form.2, data = last.cases.boot)
    m1a3 <- ivreg(form.3, data = last.cases.boot)
    
    results[[i]] <- c(m1a1$coefficients["pti"], 
                      m1a2$coefficients["pti"], 
                      m1a3$coefficients["pti"])
  }
  
  SEs <- round(apply(do.call('rbind', results), 2, sd), 2)
}

m1a1 <- ivreg(form.1, data = last.cases)
m1a2 <- ivreg(form.2, data = last.cases)
m1a3 <- ivreg(form.3, data = last.cases)

res1_pti <- coefficients(m1a1)[grep("pti", names(coefficients(m1a1)))]
res2_pti <- coefficients(m1a2)[grep("pti", names(coefficients(m1a2)))]
res3_pti <- coefficients(m1a3)[grep("pti", names(coefficients(m1a3)))]

c1 <- c(res1_pti, SEs[1])
c2 <- c(res2_pti, SEs[2])
c3 <- c(res3_pti, SEs[3])

m1 <- data.frame(rbind(c1,
                       c2,
                       c3))

colnames(m1) <- c("estimate", "std.error")
m1$term <- c("t1", "t2", "t3")
m1_df <- data.frame(as.matrix(m1)) 
m1_df$estimate <- as.numeric(as.character(m1_df$estimate))
m1_df$std.error <- as.numeric(as.character(m1_df$std.error))

g3 <- {dwplot(m1_df, 
              dot_args = list(size = 2.5), whisker_args = list(size = 0.75),  
              vline = geom_vline(xintercept = 0, colour = "grey60", linetype = 2)) %>% 
    relabel_predictors(c(t1 = "Fixed Effects", t2 = "Fixed Effects\n + Demographics", t3 = "Fixed Effects\n + Demographics\n + Case Covariates")) +
    theme_classic() + xlab("The Effect of Pretrial Incarceration on Turnout") + ylab("Model Specification") + xlim(-.2, .2)+
    ggtitle("Turnout 2016") +
    theme(plot.title = element_text(face="bold"), legend.position = "none",
          axis.text.x  = element_text(size = 12),
          axis.text.y  = element_text(size = 12),
          text = element_text(size = 13))} 

g2 <- {dwplot(m1_df2, 
              dot_args = list(size = 2.5), whisker_args = list(size = 0.75),  
              vline = geom_vline(xintercept = 0, colour = "grey60", linetype = 2)) %>% 
    relabel_predictors(c(t1 = "Fixed Effects", t2 = "Fixed Effects\n + Demographics", t3 = "Fixed Effects\n + Demographics\n + Case Covariates")) +
    theme_classic() + xlab("The Effect of Pretrial Incarceration on Turnout") + ylab("Model Specification") + xlim(-.2, .2)+
    ggtitle("Turnout 2012") +
    theme(plot.title = element_text(face="bold"), legend.position = "none",
          axis.text.x  = element_text(size = 12),
          axis.text.y  = element_text(size = 12),
          text = element_text(size = 13))} 

pdf(file = "./Figures/Figure_A05_BJPOLS.pdf", width = 12, height = 6)
ggarrange(g2, g3)
dev.off()
